package com.heima.comment.service.impl;
import java.math.BigDecimal;

import com.heima.aliyun.scan.GreenScan;
import com.heima.aliyun.scan.ScanResult;
import com.heima.comment.service.CommentRepayService;
import com.heima.feigns.UserFeign;
import com.heima.model.comment.dtos.CommentRepayDTO;
import com.heima.model.comment.dtos.CommentRepayLikeDTO;
import com.heima.model.comment.dtos.CommentRepaySaveDTO;
import com.heima.model.comment.pojos.ApComment;
import com.heima.model.comment.pojos.ApCommentRepay;
import com.heima.model.comment.pojos.ApCommentRepayLike;
import com.heima.model.comment.vo.ApCommentRepayVO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.pojos.ApUser;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Slf4j
public class CommentRepayServiceImpl implements CommentRepayService {


    @Autowired
    MongoTemplate mongoTemplate;

    /**
     * 查看更多回复内容
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadCommentRepay(CommentRepayDTO dto) {

        //参数校验  评论id不能为空  size为null 或 0 设置为10  最小日期为空 设置为当前
        if (dto.getCommentId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID,"文章id不能为空");
        }
//        Integer size = dto.getSize();
        if (dto.getSize()==null){
            dto.setSize(10);
        }
        if (dto.getMinDate()==null){
            dto.setMinDate(new Date());
        }

        //条件查询评论回复信息  条件:  commentId = 评论id and createdTime 小于 minDate  创建时间 降序  limit size
        Query query = Query.query(Criteria.where("commentId").is(dto.getCommentId())
                .and("createdTime").lt(dto.getMinDate()))
                .with(Sort.by(Sort.DEFAULT_DIRECTION, "createdTime")).limit(dto.getSize());
        List<ApCommentRepay> apCommentRepayList = mongoTemplate.find(query, ApCommentRepay.class);

        //检查是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user==null){
            //如果未登录直接 返回评论回复列表
            return ResponseResult.okResult(apCommentRepayList);
        }else {
            //如果登录，需要判断哪些回复点过赞

            //评论回复id
            List<String> commentIds = apCommentRepayList.stream().map(ApCommentRepay::getId).collect(Collectors.toList());

            Query likeRepayQuery = Query.query(Criteria.where("authorId").is(user.getId()).and("commentRepayId").in(commentIds));
            List<ApCommentRepayLike> apCommentRepayLikes = mongoTemplate.find(likeRepayQuery, ApCommentRepayLike.class);

            if (apCommentRepayLikes!=null){
                //有点过赞的回复  得到点赞回复id
                List<String> apCommentRepayLikeIds = apCommentRepayLikes.stream().map(ApCommentRepayLike::getCommentRepayId).collect(Collectors.toList());

                //遍历 当前回复列表，将每一个回复信息 封装成 vo
                List<ApCommentRepayVO> apCommentRepayVoList = new ArrayList<>();
                ApCommentRepayVO apCommentRepayVO=new ApCommentRepayVO();
                for (ApCommentRepay apCommentRepay : apCommentRepayList) {
                    BeanUtils.copyProperties(apCommentRepay,apCommentRepayVO);

                    //判断当前回复id 在点赞信息中是否存在，如果存在 operation设置为0 不存在不做处理
                    if (apCommentRepayLikeIds.contains(apCommentRepay.getId())){
                        apCommentRepayVO.setOperation((short)0);
                    }
                    apCommentRepayVoList.add(apCommentRepayVO);
                }
                return ResponseResult.okResult(apCommentRepayVoList);
            }
        }
        //没有点赞过的回复 直接返回回复集合
        return ResponseResult.okResult(apCommentRepayList);
    }

    //阿里云安全检查
    @Autowired
    GreenScan greenScan;

    @Autowired
    UserFeign userFeign;
    /**
     * 保存回复
     * @return
     */
    @Override
    public ResponseResult saveCommentRepay(CommentRepaySaveDTO dto) {

        //参数校验:    是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //回复内容安全校验  有问题替换为**
        String content = dto.getContent();
        try {
            ScanResult scanResult = greenScan.greenTextScan(content);
            String filteredContent = scanResult.getFilteredContent();
            // 如果有违规词汇 过滤内容不为空  替换内容
            if (filteredContent!=null){
                content=filteredContent;
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.info("阿里云检测失败   失败原因{}"+e.getMessage());
        }

        //根据当前登录用户的id 查询当前用户的信息 远程调用
        ResponseResult<ApUser> userById = userFeign.findUserById(user.getId());
        ApUser apUser = userById.getData();
        if (apUser==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE, "当前登录信息有误");
        }
        //根据评论id查询评论信息  检查是否存在
//        Query query = Query.query(Criteria.where("commentId").is(dto.getCommentId()));
//        ApComment apComment = mongoTemplate.findOne(query, ApComment.class);
        ApComment apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
        if (apComment!=null){
            //保存评论回复信息
            ApCommentRepay apCommentRepay =new ApCommentRepay();
            apCommentRepay.setAuthorId(apUser.getId());
            apCommentRepay.setAuthorName(apUser.getName());
            apCommentRepay.setCommentId(dto.getCommentId());
            apCommentRepay.setContent(content);
            apCommentRepay.setLikes(0);
            apCommentRepay.setCreatedTime(new Date());
            apCommentRepay.setUpdatedTime(new Date());
            mongoTemplate.insert(apCommentRepay);
        }

        //修改评论信息中回复数量 + 1
        apComment.setReply(apComment.getReply()+1);
        mongoTemplate.save(apComment);
        return ResponseResult.okResult();
    }


    /**
     * 点赞回复的评论
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveCommentRepayLike(CommentRepayLikeDTO dto) {

        //校验登录  (必须登录)
        ApUser user = AppThreadLocalUtils.getUser();
        if (user==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        // 校验回复信息是否存在
        ApCommentRepay apCommentRepay = mongoTemplate.findById(dto.getCommentRepayId(), ApCommentRepay.class);
        if (apCommentRepay==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST);
        }

        //如果是点赞  判断是否点过赞
        Query query = Query.query(Criteria.where("authorId").is(user.getId()).and("commentRepayId").is(apCommentRepay.getId()));
        ApCommentRepayLike commentRepayLike = mongoTemplate.findOne(query, ApCommentRepayLike.class);
        if (dto.getOperation()==0){
            if (commentRepayLike!=null){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST,"重复点赞");
            }

            //未点过赞， 保存点赞信息
           ApCommentRepayLike apCommentRepayLike=new ApCommentRepayLike();

           apCommentRepayLike.setAuthorId(user.getId());
           apCommentRepayLike.setCommentRepayId(dto.getCommentRepayId());
           apCommentRepayLike.setOperation((short)0);
           mongoTemplate.save(apCommentRepayLike);



            // 并将回复信息的点赞数量字段+1
            apCommentRepay.setLikes(apCommentRepay.getLikes()+1);
            mongoTemplate.save(apCommentRepay);

        }

        //如果是取消赞
        if (dto.getOperation()==1){
            if (commentRepayLike==null){
                return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"没有点赞");
            }

            //删除点赞信息
            mongoTemplate.remove(query,ApCommentRepayLike.class);
            //更新评论的点赞数量  判断够不够 不能为负数
            apCommentRepay.setLikes(apCommentRepay.getLikes()<=0 ? 0 :apCommentRepay.getLikes()-1);
            mongoTemplate.save(apCommentRepay);

        }

        //返回当前回复的最新点赞数量      数据的key:  likes
        Map<String,Object> map =new HashMap<>();

        map.put("likes",apCommentRepay.getLikes());

        return ResponseResult.okResult(map);

    }
}
